package com.benyi.util;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class Config { 
	
	private static Logger log = LoggerFactory.getLogger(Config.class);
	
    private String sFile;
    private HashMap<String,String> map;
    private String lastKey=null;
    
    public static Config getConfig(String file){
    	Config c=new Config();
    	c.setConfigFile(file); 
    	return c;
    }
    
    public Config(){  
        map=new HashMap<String,String>();
    } 
    
    public void setConfigFile(String sFile){
    	log.debug("set config property="+sFile);
    	this.sFile=sFile; 
    	load();
    }
    
    public Config(String sFile){ 
        this.sFile=sFile; 
        map=new HashMap<String,String>();
    } 
    
    public HashMap<String,String> getMap(){
    	return map;
    }
    
    public void load(){ 
    	map.clear();
    	BufferedReader f=null;
    	String file=sFile;
    	String flag="classpath:";
    	log.debug("...load from : "+sFile);
    	try{
    		if(file.startsWith(flag)){
        		file=file.substring(flag.length());
        		log.debug("...load from classpath file="+file);
        		ClassLoader loader=this.getClass().getClassLoader(); 
    			InputStream is=loader.getResourceAsStream(file);  
    			f = new BufferedReader(new InputStreamReader(is, "UTF-8"));  
        	}else{
        		log.debug("...load from  file="+sFile);
        		f = new BufferedReader(new InputStreamReader(new FileInputStream(sFile), "UTF-8"));  
        	} 
    	}catch(Exception e){
    		log.debug("...load config exception",e); 
    	} 
    	log.debug("...load config InputStream=",f); 
    	
        try{ 
        	boolean haveOmmit=false; 
            String sLine=""; 
            while(sLine!=null){
            	sLine=f.readLine(); 
            	log.debug("...load line="+sLine); 
            	
            	if(sLine==null){
            		break;
            	}
            	sLine=sLine.trim();
            	if(sLine.startsWith("/*")){ //忽略 "/*" 开始的注释行 
            		haveOmmit=true;
                    continue; 
                } 
            	if(sLine.startsWith("*/")){ //忽略 "/*" 开始的注释行 
            		if(haveOmmit){
            			haveOmmit=false;
            		} 
                    continue; 
                } 
            	if(haveOmmit){
            		continue;
            	}
                if(sLine.startsWith("#")){ //忽略 "#" 开始的注释行 
                    continue; 
                }  
                if(sLine.startsWith("//")){ //忽略 "//" 开始的注释行 
                    continue; 
                }
                int c=sLine.indexOf(" #");
                if(c>0){
                	sLine=sLine.substring(0,c);
                }
                c=sLine.indexOf(" //");
                if(c>0){
                	sLine=sLine.substring(0,c);
                } 
                addItem(sLine);
            }             
        }catch(Exception e){
        	log.debug("...parse config exception:",e);  
        }finally{
        	if(f!=null){
        		try{
        			f.close();
        		}catch(Exception e){}        		
        	}
        }
        log.debug("--end of confg:"+toString());
    } 


    private void addItem(String sMsg){ 
    		
        if(sMsg==null || sMsg.length()==0){ 
            return; 
        } 
        int k=sMsg.indexOf("/ "); //继续上面一行
        if(k>=0) {
        	sMsg=sMsg.substring(k+2);
        	sMsg=sMsg.trim();   
        	
        	if(lastKey == null) {
        		return;
        	}
        	String v=map.get(lastKey);
        	if(v!=null) {
        		v += sMsg;
        		 map.put(lastKey, v);
        	}
        	return;
        }
        
        sMsg=sMsg.trim();    
        int i=sMsg.indexOf("="); 
        if(i<1 || i==sMsg.length()-1){
            return; 
        } 
        String sKey=sMsg.substring(0,i); 
        String sValue=sMsg.substring(i+1);
        
        sKey=sKey.trim().toLowerCase();
        sValue=sValue.trim();        
        map.put(sKey, sValue);
        lastKey = sKey;
    } 
    
    public String get(String key){
    	if(key==null){
    		return null;
    	}
    	String s=map.get(key.toLowerCase());
    	return s;
    }
    
    public int getInt(String key){
    	if(key==null){
    		return 0;
    	}
    	String s=map.get(key.toLowerCase());
    	try{
    		return Integer.parseInt(s);
    	}catch(Exception e){}
    	
    	return 0;
    }
    
    public int getInt(String key,int v){
    	if(key==null){
    		return v;
    	}
    	String s=map.get(key.toLowerCase());
    	try{
    		return Integer.parseInt(s);
    	}catch(Exception e){}
    	
    	return v;
    }
    
    
    public boolean getBool(String key){
    	if(key==null){
    		return true;
    	}
    	String s=map.get(key.toLowerCase());
    	try{
    		if("1".equalsIgnoreCase(s)){
    			return true;
    		}
    		if("true".equalsIgnoreCase(s)){
    			return true;
    		}
    	}catch(Exception e){}
    	
    	return false;
    }
    
    public void put(String key,String v){
    	map.put(key.toLowerCase(), v);
    }
    
    /**
     * 替换所有值
     * @param olds
     * @param news
     * @param bSep - true 替换 "/\"为系统字符： File.separator
     * @return
     */
    public int replace(String olds,String news,boolean bSep){
    	Object []os=map.keySet().toArray();
    	int n=0;
    	String key,val;
    	for(int i=0;i<os.length;i++){
    		key=(String)os[i];
    		val=map.get(key);
    		if(val.indexOf(olds)>=0){
    			val=val.replace(olds, news);
    			if(bSep){
    				val=val.replace("/", File.separator);
    				val=val.replace("\\", File.separator);
    			} 
    			map.put(key, val);
    			n++;
    		}
    	}
    	return n;
    }
    
    public String getFilePath(){
    	return sFile;
    }
    
    public String toString(){
    	StringBuilder sb=new StringBuilder();
    	sb.append("file:"+sFile);
    	Object []os=map.keySet().toArray();
    	for(int i=0;i<os.length;i++){
    		sb.append("\r\n");
    		sb.append(os[i]+" = "+get((String)os[i]));
    	}
    	return sb.toString();
    }
    
    public static void main(String []args) {
    	Config c=Config.getConfig("classpath:config.ini");
    	System.out.println("------------------------------");
    	 
    }
} 